import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect, IfPermission } from '@folio/stripes/core';
import get from 'lodash/get';
import {
  MultiColumnList,
  DropdownMenu,
  Dropdown,
  Button,

} from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import SearchForm from '../../components/party-manage/search-form';
import VerifyCafe from '../../components/party-manage/verify-cafe';
import RevealQrCode from '../../components/party-manage/reveal-qr-code';
import PartyPreview from '../../components/party-manage/cafe-preview';

class List extends Component {
  static manifest = Object.freeze({

    partyQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    ActivityMessageRecords: {
      type: 'okapi',
      path: 'party/info',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'limit',
      records: 'partyGroup',
      GET: {
        params: {
          query: '(isDel = 0 and isCalendar = 0  %{partyQuery} ) sortby metadata.createdDate/sort.descending  '
        }
      }
    },
    activityMessageHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/info'
    },
    partyApproveHttpRequest: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/info/approve'
    },
    activityRegistrationRequest: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/reserve',
      params: {
        query: ''
      }
    },
    activityClassificationRequest: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/property'
    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({

      partyQuery: PropTypes.string,
      activityMessageHttpInvoke: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }),
      partyApproveHttpRequest: PropTypes.shape({
        PUT: PropTypes.func.isRequired
      }),
      activityRegistrationRequest: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),
      activityClassificationRequest: PropTypes.shape({
        GET: PropTypes.func.isRequired
      })
    }).isRequired,
    dictionary: PropTypes.object,
    okapi:PropTypes.object,
    toModel:PropTypes.func,
    intl:PropTypes.object
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchForm: {},
      editOpen: false,
      editParams: {},
      verifyOpen: false,
      verifyParams: {},
      openCodeImageFlag: false,
      ascriptionList: [],
      optionCategoryList: [],
      isOpen: false,
      operator: {},
      preview:''
    };
    // console.log(this.props.stripes.hasPerm('ui-party.property.manage.view.edit'))
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    this.getClassificationList();
    const { currentUser } = this.props.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  componentDidUpdate() {
    this.source.update(this.props, 'ActivityMessageRecords');
  }

  componentWillUnmount() {
    const { mutator, resources } = this.props;

    mutator.partyQuery.replace('');
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    let query = '';
    if (formData) {
      if (formData.propertyName) {
        query += ` and propertyName = ${formData.propertyName}* `;
      }
      if (formData.approval) {
        query += ` and approval = ${formData.approval} `;
      }
      if (formData.name) {
        query += ` and partyName = ${formData.name}* `;
      }
      if (formData.partyStartDate && formData.partyEndDate) {
        query += ` and partyStartDate >= ${formData.partyStartDate} 00:00:00 `;
        query += ` and partyEndDate <= ${formData.partyEndDate} 23:59:59 `;
      }
    }

    mutator.partyQuery.replace(query);
    if (this.source) {
      this.source.update(this.props, 'ActivityMessageRecords');
      this.setState({
        searchForm: formData
      });
    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  openReview = item => {
    const verifyOpen = this.state.verifyOpen;
    
    const { mutator } = this.props;

    if (!verifyOpen) {
      mutator.activityMessageHttpInvoke
        .GET({ path: `party/info/${item.id}` })
        .then(res => {
          this.setState({
            verifyOpen: true,
            verifyParams: res
          });
        });
    } else {
      this.setState({
        verifyOpen: false
      });
    }
  };

  verifyDataCommit = item => {
    if (item) {
      const { mutator } = this.props;
      item.operator = this.state.operator;
      delete item.operator.addresses;
      delete item.operator.preferredContactTypeId;
      delete item.operator.servicePoints;
      delete item.operator.curServicePoint;
      delete item.operator.dateOfBirth;
      mutator.partyApproveHttpRequest.PUT(item).then(re => {
        if (this.source) {
          this.source.update(this.props, 'ActivityMessageRecords');
          this.setState({
            verifyOpen: false,
            verifyParams: {}
          });
        }
      });
    }
  };

  checkInCode = (val, type) => {
    const _this = this;
    const openCodeImageFlag = this.state.openCodeImageFlag;
    this.setState(
      {
        openCodeImageFlag: !openCodeImageFlag
      },
      () => {
        if (this.state.openCodeImageFlag && type) {
          // 执行子组件方法
          const object = {
            type,
            openCodeImageObject: val
          };
          setTimeout(() => {
            _this.refs.codeImage.getCheckCodeImage(object);
          }, 300);
        }
      }
    );
  };

  deleteData = item => {
    const { GET } = this.props.mutator.activityRegistrationRequest;
    const { DELETE } = this.props.mutator.ActivityMessageRecords;
    const { intl } = this.props;
    const query = `(isDel = 0 and partyId == *${item.id}*)`;
    GET({ params: { query } }).then(res => {
      if (res.totalRecords > 0) {
        if (confirm(intl.formatMessage({ id: 'ui-party.loans.columns.party.deleteRemind' }))) {
          DELETE({ id: item.id });
          this.source.update(this.props, 'ActivityMessageRecords');
        }
      } else if (confirm(intl.formatMessage({ id: 'ui-party.loans.columns.party.deleteRemind' }))) {
        DELETE({ id: item.id });
        this.source.update(this.props, 'ActivityMessageRecords');
      }
    });
  };

  getClassificationList = () => {
    const params = {
      params: {
        query: '( isDel = 0 and parentId <> 0 )'
      }
    };
    const { intl } = this.props;
    const { GET } = this.props.mutator.activityClassificationRequest;
    GET(params).then(response => {
      const list = response.propertyGroup;

      if (list) {
        const ascriptionList = [
          {
            value: '',
            label: intl.formatMessage({ id: 'ui-party.please.select' }) + intl.formatMessage({ id:'ui-party.loans.columns.property.parentName' }),
            id: ''
          }
        ];

        list.forEach(value => {
          if (value) {
            const tmp = {
              value: value.name,
              label: value.name,
              id: value.id
            };

            ascriptionList.push(tmp);
          }
        });
        this.setState({
          ascriptionList

        });
      }
    });
  };



  category = item => {
    const { intl } = this.props;
    const option = [
      {
        label: intl.formatMessage({ id: 'ui-party.loans.columns.party.needReserveAndNotApproval' }),
        value: 1
      },
      {
        label: intl.formatMessage({ id: 'ui-party.loans.columns.party.needReserveAndNeedApproval' }),
        value: 2
      },
      {
        label: intl.formatMessage({ id: 'ui-party.loans.columns.party.notReserveAndNotApproval' }),
        value: 3
      }
    ];

    let result = '';
    option.forEach(a => {
      if (item.category === a.value) {
        result = a.label;
      }
    });
    return result;
  };
  killPreview=(nextAction=null) => {
    this.setState({
      preview:''
    },()=>{
      if(nextAction){
        nextAction()
      }
    });
  }
  edit=(id)=>{
    const {toModel} = this.props
    this.killPreview(()=>{
      toModel('/party/info/edit',{id:id})
    })
  }

  qrCode=(item,type)=>{
    this.killPreview(()=>{
      this.checkInCode(item, type);
    })
  }
  approval=(item)=>{
    this.killPreview(()=>{
      this.openReview(item)
    })
  }
  del=(id)=>{
    this.killPreview(()=>{
      this.deleteData({id})
    })
  }
  render() {
    const previewAction = {
      edit:(id)=>this.edit(id),
      qrCode:(item,type)=>this.qrCode(item,type),
      approval: (item)=>this.approval(item),
      del:(id)=>this.del(id)
    }
    const { resources, toModel } = this.props;
    const able = document.getElementsByClassName('mclScrollable---IM56u');
    if (able && able[0]) {
      able[0].style.width = '102%';
    }
    if (this.source) {
      this.source.update(this.props, 'ActivityMessageRecords');
    }
    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'ActivityMessageRecords.records', []);

    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      partyName: (
        <FormattedMessage id="ui-party.loans.columns.party.partyName" />
      ),
      propertyName: (
        <FormattedMessage id="ui-party.loans.columns.party.propertyName" />
      ),
      quota: (
        <FormattedMessage id="ui-party.loans.columns.party.quota" />
      ),
      category: (
        <FormattedMessage id="ui-party.loans.columns.party.category" />
      ),
      venue: (
        <FormattedMessage id="ui-party.loans.columns.party.venue" />
      ),
      facName: (
        <FormattedMessage id="ui-party.loans.columns.party.facName" />
      ),
      reserveStartDate: (
        <FormattedMessage id="ui-party.loans.columns.party.reserveDate" />
      ),

      partyStartDate: (
        <FormattedMessage id="ui-party.loans.columns.party.partyDate" />
      ),
      approval: (
        <FormattedMessage id="ui-party.loans.columns.party.approvalStatus" />
      ),
      status: (
        <FormattedMessage id="ui-party.loans.columns.party.status" />
      ),
      edit: <FormattedMessage id="ui-party.loans.columns.operating" />,
      remark: (
        <FormattedMessage id="ui-party.loans.columns.property.remark" />
      )
    };

    return (
      <div data-test-application-settings-general-message>
        {/* <PartyPreview></PartyPreview> */}
        {this.state.preview}
        {/* 二维码弹窗 */}
        {this.state.openCodeImageFlag ? (
          <RevealQrCode
            openCodeImageFlag={this.state.openCodeImageFlag}
            ref="codeImage"
            checkInCode={this.checkInCode}
            {...this.props}
          />
        ) : (
          ''
        )}
        <VerifyCafe
          verifyOpen={this.state.verifyOpen}
          verifyParams={this.state.verifyParams}
          openReview={this.openReview}
          verifyDataCommit={this.verifyDataCommit}
          {...this.props}
        />
        <SearchForm
          onSubmit={this.search}
          add={this.add}
          ascriptionList={this.state.ascriptionList}
          toModel={toModel}
          {...this.props}
        />
        <MultiColumnList
          maxHeight={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          onRowClick={(e,data)=>{
            const then = this;
            this.setState((preState)=>{
               let preview = <PartyPreview initialValues={data} closeModal={then.killPreview} {...previewAction}/>
               return {preview:preview}
            })
          }}
          interactive={false}
          columnWidths={{
            propertyName: '120px',
            serialNumber: '60px',
            partyStartDate: '160px',
            reserveStartDate: '160px',
            partyName: '200px',
            quota: '90px',
            category: '150px',
            approval: '93px',
            status: '93px',
            edit: '160px',
            remark: '120px'
          }}
          visibleColumns={[
            'serialNumber',
            'partyName',
            'propertyName',
            'quota',
            'category',
            'venue',
            'facName',
            'reserveStartDate',
            'partyStartDate',
            'approval',
            'status',
            'remark',

          ]}
          formatter={{
            approval: item => {
              if (item.approval === 0) {
                return [<div><FormattedMessage id="ui-party.loans.columns.party.unapproved" /></div>];
              }
              if (item.approval === 1) {
                return [<div><FormattedMessage id="ui-party.loans.columns.party.approved" /></div>];
              }
              if (item.approval === 2) {
                return [<div><FormattedMessage id="ui-party.loans.columns.party.reject" /></div>];
              }

              return [<div />];
            },
            status: item => [<div>{item.status === 0 ? <FormattedMessage id="ui-party.loans.columns.party.noneffective" /> : <FormattedMessage id="ui-party.loans.columns.party.effective" />}</div>],
            facName: item => [
              <div
                title={item.facName}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {item.facName}
              </div>
            ],
            remark: item => [
              <div
                title={item.remark}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {item.remark}
              </div>
            ],
            category: item => [
              <div
                title={item.category}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {this.category(item)}
              </div>
            ],
            partyName: item => [
              <div
                title={item.partyName}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
                // onClick={() => {
                //   toModel('/party/info/edit',{id:item.id})
            // }}
              >
                {item.partyName}
              </div>
            ],
            edit: item => [
              <IfPermission perm="ui-party.property.manage.view.edit">
                <Button
                  onClick={() => {
                    toModel('/party/info/edit', { id:item.id });
                  }}
                >
                  <FormattedMessage id="ui-party.loans.columns.operating.edit" />
                </Button>
              </IfPermission>,
              <Dropdown
                label={<FormattedMessage id="ui-party.more" />}
                renderMenu={({ onToggle }) => (
                  <div>
                    <DropdownMenu
                      data-role="menu"
                      aria-label="available permissions"
                      onToggle={this.onToggle}
                      minWidth="100px"
                    >
                      <div style={{ textAlign: 'center' }}>
                        <ul>
                          <IfPermission perm="ui-party.party.approval">
                            <li>
                              <Button onClick={() => this.openReview(item)}>
                                <FormattedMessage id="ui-party.loans.columns.operating.approval.party" />
                              </Button>
                            </li>
                          </IfPermission>
                          <IfPermission perm="ui-party.info.manage.view.reserve.qrcode">
                            <li>
                              <Button
                                onClick={() => {
                                  this.checkInCode(item, 'regist');
                                }}
                              >
                                <FormattedMessage id="ui-party.loans.columns.operating.reserve.qrcode" />
                              </Button>
                            </li>
                          </IfPermission>
                          <IfPermission perm="ui-party.info.manage.view.attend.qrcode">
                            {item.reserveStartDate == null ? (
                              ''
                            ) : (

                              <li>
                                <Button
                                  onClick={() => {
                                    this.checkInCode(item, 'check');
                                  }}
                                >
                                  <FormattedMessage id="ui-party.loans.columns.operating.attend.qrcode" />
                                </Button>
                              </li>

                            )}
                          </IfPermission>
                          <IfPermission perm="ui-party.info.manage.view.delete">
                            <li>
                              <Button
                                style={{
                                  border: '1px solid #900',
                                  color: ' #900'
                                }}
                                onClick={() => {
                                  this.deleteData(item);
                                }}
                              >
                                <FormattedMessage id="ui-party.loans.columns.operating.party.delete" />

                              </Button>
                            </li>
                          </IfPermission>
                        </ul>
                      </div>
                    </DropdownMenu>
                  </div>
                )}
              />
            ],
            reserveStartDate: item => {
              if (item.reserveStartDate == null) {
                return [];
              } else {
                return (
                  <div
                    title={item.reserveStartDate}
                    style={{
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis'
                    }}
                  >
                    {`${item.reserveStartDate} - ${item.reserveEndDate}`}

                  </div>
                );
              }
            },

            partyStartDate: item => [
              <div
                title={`${item.partyStartDate} ${item.partyEndDate}  `}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {`${item.partyStartDate} - ${item.partyEndDate}`}

              </div>
            ],
            serialNumber: item => [<span>{item.rowIndex + 1}</span>],

            attendStartDate: item => {
              if (item.attendStartDate === null) {
                return [];
              } else {
                return (
                  <div
                    title={`${item.attendStartDate} ${item.attendEndDate}`}
                    style={{
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis'
                    }}
                  >
                    {`${item.attendStartDate} - ${item.attendEndDate}`}
                  </div>
                );
              }
            }
          }}
        />
      </div>
    );
  }
}

export default injectIntl(stripesConnect(List));
